package logic

import (
	"context"
	"errors"
	"friend/common"
	"friend/models"

	"friend/internal/svc"
	"friend/pb/friend"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddApplyLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddApplyLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddApplyLogic {
	return &AddApplyLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// AddApply 好友申请新增
func (l *AddApplyLogic) AddApply(in *friend.ApplyInfo) (*friend.Empty, error) {
	existApply, err := l.svcCtx.FriendApplyModel.FindOneByFromUserIdToUserId(l.ctx, in.FromUserId, in.ToUserId)
	if err != nil {
		return nil, err
	}
	if existApply != nil && existApply.Id > 0 {
		return nil, errors.New("friend apply already exist")
	}

	result, err := l.svcCtx.FriendApplyModel.Insert(l.ctx, &models.FriendApply{
		FromUserId: in.FromUserId,
		ToUserId:   in.ToUserId,
		Message:    in.Message,
		Status:     common.FriendApplyStatusWait,
	})
	if err != nil {
		return nil, err
	}

	lastID, err := result.LastInsertId()
	if err != nil {
		return nil, err
	}

	in.Id = lastID
	l.Logger.Infof("add apply: %v", in)
	return &friend.Empty{}, nil
}
